<template>
  <div class="uploader-panel">
    <div class="uploader-title">
      <span>上传任务</span>
      <span class="tips">（仅展示本次上传任务）</span>
    </div>
    <div class="file-list">
      <div v-for="(item, index) in fileList" :key="index" class="file-item">
        <div class="upload-panel">
          <div class="file-name">
            {{ item.fileName }}
          </div>
          <div class="progress" v-if="
                item.status == STATUS.uploading.value ||
                item.status == STATUS.upload_seconds.value ||
                item.status == STATUS.upload_finish.value
              ">
            <el-progress
              :percentage="item.uploadProgress"
            >
            </el-progress>
          </div>
          <!-- 图标 -->
          <div class="upload-status">
            <span
              :class="['iconfont', 'icon-' + STATUS[item.status].icon]"
              :style="{ color: STATUS[item.status].color }"
            ></span>
            <!-- 状态描述 -->
            <span class="status" :style="{ color: STATUS[item.status].color }">
              {{
                item.status == "fail" ? item.errorMsg : STATUS[item.status].desc
              }}
            </span>
            <!-- 上传中 -->
            <span
              class="upload-info"
              v-if="item.status == STATUS.uploading.value"
            >
              {{ proxy.sizeToStr.size2Str(item.uploadSize) }}/{{
                proxy.sizeToStr.size2Str(item.totalSize)
              }}
            </span>
          </div>
        </div>
        <div class="op">
          <!-- MD5 -->
          <el-progress
            type="circle"
            :width="50"
            :percentage="item.md5Progress"
            v-if="item.status == STATUS.init.value"
          >
          </el-progress>
          <div class="btn">
            <!-- 继续上传按钮 -->
            <span v-if="item.status === STATUS.uploading.value">
              <Icon
                :width="28"
                class="btn-item"
                iconName="upload"
                v-if="item.pause"
                title="上传"
                @click="startUpload(item.uid)"
              ></Icon>
              <!-- 暂停上传 -->
              <Icon
                v-else
                :width="28"
                class="btn-item"
                iconName="pause"
                title="暂停"
                @click="pauseUpload(item.uid)"
              ></Icon>
            </span>
            <!-- 删除上传 -->
            <Icon
              v-if="
                item.status != STATUS.init.value &&
                item.status != STATUS.upload_finish &&
                item.status != STATUS.upload_seconds
              "
              :width="28"
              class="del btn-item"
              iconName="del"
              title="删除"
              @click="delUpload(item.uid, index)"
            ></Icon>
            <!-- 清除 -->
            <Icon
              v-if="
                item.status == STATUS.upload_finish ||
                item.status == STATUS.upload_seconds
              "
              :width="28"
              class="clean btn-item"
              iconName="clean"
              title="清除"
              @click="delUpload(item.uid, index)"
            ></Icon>
          </div>
        </div>
      </div>

      <NoData msg="暂无上传任务" v-if="fileList.length == 0"></NoData>
    </div>
  </div>
</template>

<script setup>

import { ref, reactive, getCurrentInstance } from "vue";
import { UploadFile } from "@/api/fileInfo";
const { proxy } = getCurrentInstance();
import SparkMD5 from "spark-md5";
const STATUS = {
  emptyfile: {
    value: "emptyfile",
    desc: "文件为空",
    color: "#F75000",
    icon: "close",
  },
  fail: {
    value: "fail",
    desc: "上传失败",
    color: "#F75000",
    icon: "close",
  },
  init: {
    value: "init",
    desc: "解析中",
    color: "#e6a23c",
    icon: "clock",
  },
  uploading: {
    value: "uploading",
    desc: "上传中",
    color: "#409eff",
    icon: "upload",
  },
  upload_finish: {
    value: "upload_finish",
    desc: "上传完成",
    color: "#67c23a",
    icon: "ok",
  },
  upload_seconds: {
    value: "upload_seconds",
    desc: "秒传",
    color: "#67c23a",
    icon: "ok",
  },
};
const fileList = ref([]);

// 一个分片 1m
const chunkSize = 1024 * 1024;
const delList = ref([]);
const addFile = async (file, filePid) => {
  const fileItem = {
    // 上传的文件
    file: file,
    // 文件uid
    uid: file.uid,
    // 计算md5进度
    md5Progress: 0,
    // 文件md5
    md5: null,
    // 文件名
    fileName: file.name,
    // 上传状态
    status: STATUS.init.value,
    // 已上传大小
    uploadSize: 0,
    // 文件总大小
    totalSize: file.size,
    // 上传进度
    uploadProgress: 0,
    // 暂停
    pause: false,
    // 当前分片
    chunkIndex: 0,
    // 父级id
    filePid: filePid,
    // 错误信息
    errorMsg: null,
  };
  fileList.value.unshift(fileItem);
  // 文件大小为空 不进行上传
  if (fileItem.totalSize == 0) {
    fileItem.status = STATUS.emptyfile.value;
    return;
  }
  let md5FileUid = await computeMd5(fileItem);
  // md5为空
  if (md5FileUid == null) {
    return;
  }

  // 上传文件
  uploadFile(md5FileUid);
};
// 父组件访问子组件方法要暴露出去
defineExpose({ addFile });

// 计算文件md5
const computeMd5 = (fileItem) => {
  let file = fileItem.file;
  //. 定义切片大小 
  //如果浏览器不支持标准的 slice 方法，就会依次尝试使用 mozSlice 和 webkitSlice 方法来获取文件的切片。
  let blobSlice =
    File.prototype.slice ||
    File.prototype.mozSlice ||
    File.prototype.webkitSlice;
  // 计算切片数量
  let chunks = Math.ceil(file.size / chunkSize);
  let currentChunk = 0;
  // 创建 SparkMD5 实例用于计算 MD5 值
  let spark = new SparkMD5.ArrayBuffer();
  let fileReader = new FileReader();
  // 定义加载下一个切片的函数
  // 根据当前切片序号和切片大小，读取文件的下一个切片内容，以二进制数组的形式进行处理。
  let loadNext = () => {
    let start = currentChunk * chunkSize;
    let end = start + chunkSize >= file.size ? file.size : start + chunkSize;
    // 读取切片内容
    fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  };
  // 开始加载第一个切片
  loadNext();
  // 返回一个 Promise 对象
  return new Promise((resolve, reject) => {
    // 通过文件 UID 获取相应的文件对象
    let resultFile = getFileByUid(file.uid);
    fileReader.onload = (e) => {
      // 将读取的切片内容添加到 SparkMD5 实例中
      spark.append(e.target.result);
      currentChunk++;
      if (currentChunk < chunks) {
        let percent = Math.floor((currentChunk / chunks) * 100);
        // 更新文件对象的 MD5 计算进度
        resultFile.md5Progress = percent;
        // 加载下一个切片
       
        loadNext(); // 如果切换为继续状态，则立即加载下一个切片
      
      } else {
        // 完成所有切片的加载，获取最终的 MD5 值
        let md5 = spark.end();
        spark.destroy();
        // 更新文件对象的 MD5 计算进度为 100%
        resultFile.md5Progress = 100;
        // 更新文件状态为上传中
        resultFile.status = STATUS.uploading.value;
        // 存储计算得到的 MD5 值
        resultFile.md5 = md5;
        resolve(fileItem.uid);
      }
    };
    fileReader.onerror = () => {
      // 更新文件对象的 MD5 计算进度为 -1（表示计算失败）
      resultFile.md5Progress = -1;
      // 更新文件状态为上传失败
      resultFile.status = STATUS.fail.value;
      // 返回文件 UID
      resolve(fileItem.uid);
    };
  }).catch((error) => {
    console.log(error);
    return null;
  });
};
// 获取文件
const getFileByUid = (uid) => {
  let file = fileList.value.find((item) => {
    return item.file.uid === uid;
  });
  return file;
};
const emit = defineEmits(["uploadCallback"]);
const pauseUpload = (uid)=>{
  let currentFile = getFileByUid(uid);
  currentFile.pause = true;
  
}
const startUpload = (uid) => {
  let currentFile = getFileByUid(uid);
  currentFile.pause = false;
  // 继续上传之前暂停的文件
  uploadFile(uid, currentFile.chunkIndex);
}
// 删除文件 取消上传
const delUpload = (uid, index) => {
  // let currentFile = getFileByUid(uid);
  // currentFile.status = STATUS.fail.value;
  // currentFile.pause = true;
  delList.value.push(uid);
  fileList.value.splice(index, 1);
}
// 上传文件
const uploadFile = async (uid, chunkIndex) => {
  chunkIndex = chunkIndex ? chunkIndex : 0;
  // 分片上传
  let currentFile = getFileByUid(uid);

  const file = currentFile.file;
  const fileSize = currentFile.totalSize;
  const chunks = Math.ceil(fileSize / chunkSize);
  for (let i = chunkIndex; i < chunks; i++) {
    let delIndex = delList.value.indexOf(uid);
    if (delIndex != -1) {
      delList.value.splice(delIndex, 1);
      break;
    }
    currentFile = getFileByUid(uid);
    if (currentFile.pause ||currentFile.status == STATUS.fail.value) {
      break;
    }
    
    let start = i * chunkSize;
    let end = start + chunkSize >= fileSize ? fileSize : start + chunkSize;
    let chunkFile = file.slice(start, end);
    let params = {
      file: chunkFile,
      fileName: file.name,
      fileMd5: currentFile.md5,
      chunkIndex: i,
      chunks: chunks,
      fileId: currentFile.fileId,
      filePid: currentFile.filePid,
    };
    let uploadResult = await UploadFile(
      params,
      (errorMsg) => {
        currentFile.status = STATUS.fail.value;
        currentFile.errorMsg = errorMsg;
      },
      (event) => {
        let loaded = event.loaded;
        if (loaded > fileSize) {
          loaded = fileSize;
        }
        currentFile.uploadSize = i * chunkSize + loaded;
        currentFile.uploadProgress = Math.floor(
          (currentFile.uploadSize / fileSize) * 100
        );
      }
    );
    if (uploadResult == null) {
      break;
    }

    currentFile.fileId = uploadResult.data.fileId;
    currentFile.status = STATUS[uploadResult.data.status].value;
    currentFile.chunkIndex = i;
    if (
      uploadResult.data.status == STATUS.upload_seconds.value ||
      uploadResult.data.status == STATUS.upload_finish.value
    ) {
      // 上传完毕 进度条赋值100
      currentFile.uploadProgress = 100;
      
      // 上传完毕刷新文件列表
      emit("uploadCallback");
      break;
    }
  }
};
</script>

<style lang="scss" scoped>
.uploader-panel {
  .uploader-title {
    border-bottom: 1px solid #ddd;
    line-height: 40px;
    padding: 0px 10px;
    font-size: 15px;
    .tips {
      font-size: 13px;
      color: rgb(169, 169, 169);
    }
  }
  .file-list {
    overflow: auto;
    padding: 10px 0px;
    min-height: calc(100vh / 2);
    max-height: calc(100vh - 120px);
    .file-item {
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 3px 10px;
      background-color: #fff;
      border-bottom: 1px solid #ddd;
    }
    .file-item:nth-child(even) {
      background-color: #fcf8f4;
    }
    .upload-panel {
      flex: 1;
      .file-name {
        color: rgb(64, 62, 62);
      }
      .upload-status {
        display: flex;
        align-items: center;
        margin-top: 5px;
        .iconfont {
          margin-right: 3px;
        }
        .status {
          color: red;
          font-size: 13px;
        }
        .upload-info {
          margin-left: 5px;
          font-size: 12px;
          color: rgb(112, 111, 111);
        }
      }
      .progress {
        height: 10px;
      }
    }
    .op {
      width: 100px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .btn {
        .btn-item {
          cursor: pointer;
        }
        .del,
        .clean {
          margin-left: 5px;
        }
      }
    }
  }
}
</style>